package com.cjjd.c.feature.subscribe.info;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.View;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps2d.AMap;
import com.amap.api.maps2d.AMap.InfoWindowAdapter;
import com.amap.api.maps2d.AMap.OnInfoWindowClickListener;
import com.amap.api.maps2d.AMap.OnMapClickListener;
import com.amap.api.maps2d.AMap.OnMarkerClickListener;
import com.amap.api.maps2d.MapView;
import com.amap.api.maps2d.model.BitmapDescriptorFactory;
import com.amap.api.maps2d.model.LatLng;
import com.amap.api.maps2d.model.Marker;
import com.amap.api.maps2d.model.MarkerOptions;
import com.amap.api.services.core.AMapException;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.route.BusRouteResult;
import com.amap.api.services.route.DrivePath;
import com.amap.api.services.route.DriveRouteResult;
import com.amap.api.services.route.RideRouteResult;
import com.amap.api.services.route.RouteSearch;
import com.amap.api.services.route.RouteSearch.DriveRouteQuery;
import com.amap.api.services.route.RouteSearch.OnRouteSearchListener;
import com.amap.api.services.route.WalkRouteResult;
import com.bruce.pickerview.popwindow.DatePickerPopWin;
import com.cjjd.c.EventBusKeys;
import com.cjjd.c.R;
import com.cjjd.c.ShareKeys;
import com.cjjd.c.base.BaseActivity;
import com.cjjd.c.bean.HttpResult;
import com.cjjd.c.bean.ListResult;
import com.cjjd.c.bean.subscribe.HotelInfo;
import com.cjjd.c.bean.subscribe.HotelRoomShowModel;
import com.cjjd.c.bean.subscribe.HotelRoomShowModel.HotelRoomTypeShowModel;
import com.cjjd.c.feature.subscribe.select_hotel.AskActivity;
import com.cjjd.c.http.CallbackImpl;
import com.cjjd.c.http.JsonUtils;
import com.cjjd.c.utils.AMapUtil;
import com.cjjd.c.utils.DateTimeUtil;
import com.cjjd.c.utils.ImageUtil;
import com.cjjd.c.utils.LogUtil;
import com.cjjd.c.utils.SharePrefUtil;
import com.cjjd.c.utils.ToastUtil;
import com.cjjd.c.view.route.DrivingRouteOverLay;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Response;

/**
 * ----------------------------------
 * Created by xyd on 2017/11/29.
 * <p/>
 * 描  述：
 * <p/>
 * 修订历史:
 * ----------------------------------
 */

public class HotelDetailActivity extends BaseActivity implements OnMapClickListener,
        OnMarkerClickListener, OnInfoWindowClickListener, InfoWindowAdapter, OnRouteSearchListener {
    @Bind(R.id.tv_detail_title)
    TextView tvDetailTitle;
    @Bind(R.id.tv_hotel_point)
    TextView tvHotelPoint;
    @Bind(R.id.tv_evaluate)
    TextView tvEvaluate;
    @Bind(R.id.tv_open_time)
    TextView tvOpenTime;
    @Bind(R.id.iv_hotel_logo)
    ImageView ivHotelLogo;

    @Bind(R.id.tv_location_name)
    TextView tv_location_name;
    @Bind(R.id.route_map)
    MapView mapView;
    @Bind(R.id.tv_km)
    TextView tv_km;
    @Bind(R.id.tv_time)
    TextView tv_time;

    @Bind(R.id.tv_live_time)
    TextView tvLiveTime;
    @Bind(R.id.tv_live_weekday)
    TextView tvLiveWeekday;
    @Bind(R.id.tv_leave_time)
    TextView tvLeaveTime;
    @Bind(R.id.tv_leave_weekday)
    TextView tvLeaveWeekday;
    @Bind(R.id.el_rooms)
    ExpandableListView elRooms;


    private AMap aMap;
    private RouteSearch mRouteSearch;
    private DriveRouteResult mDriveRouteResult;
    private LatLonPoint mStartPoint = new LatLonPoint(39.942295, 116.335891);//起点，116.335891,39.942295
    private LatLonPoint mEndPoint = new LatLonPoint(39.995576, 116.481288);//终点，116.481288,39.995576
    private final int ROUTE_TYPE_DRIVE = 2;


    private HotelDetailExpandableListAdapter selectHomeExpandableListAdapter;

    //
    private ArrayList<HotelRoomShowModel> groupTittles;
    private ArrayList<ArrayList<HotelRoomTypeShowModel>> groupDatas;

    private String hotelUuid = "";

    // 选择日期的起始时间
    private String startDay;
    private String endDay;

    @Override
    public Fragment getContentFragment() {
        return null;
    }

    @Override
    public int getContentView() {
        return R.layout.activity_hotel_detail;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ButterKnife.bind(this);
        EventBus.getDefault().register(this);

        hotelUuid = getIntent().getStringExtra("hotelUuid");
        initLoaction();

        mapView.onCreate(savedInstanceState);
        init();
        setfromandtoMarker();
        searchRouteResult(ROUTE_TYPE_DRIVE, RouteSearch.DrivingDefault);

        initView();
        getHotelInfo();
        getHotelAvailableRoomTypeList();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        ButterKnife.unbind(this);
    }

    /**
     * 初始化AMap对象
     */
    private void init() {
        if (aMap == null) {
            aMap = mapView.getMap();
        }
        registerListener();
        mRouteSearch = new RouteSearch(this);
        mRouteSearch.setRouteSearchListener(this);
    }

    /**
     * 注册监听
     */
    private void registerListener() {
        aMap.setOnMapClickListener(this);
        aMap.setOnMarkerClickListener(this);
        aMap.setOnInfoWindowClickListener(this);
        aMap.setInfoWindowAdapter(this);

    }

    private void setfromandtoMarker() {
        aMap.addMarker(new MarkerOptions()
                .position(AMapUtil.convertToLatLng(mStartPoint))
                .icon(BitmapDescriptorFactory.fromResource(R.drawable.start)));
        aMap.addMarker(new MarkerOptions()
                .position(AMapUtil.convertToLatLng(mEndPoint))
                .icon(BitmapDescriptorFactory.fromResource(R.drawable.end)));
    }


    //<editor-fold desc="自动定位">
    private AMapLocationClient mLocationClient;

    private double latitude = -1;    // 纬度
    private double longitude = -1;   // 经度

    private void initLoaction() {

        mLocationClient = new AMapLocationClient(mContext);
        AMapLocationClientOption option = new AMapLocationClientOption();
        // 默认采用连续定位模式, 设置定位间隔,单位毫秒,默认为2000ms，最低1000ms。
        //option.setInterval(3000);
        option.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        // 如果您需要使用单次定位 true, 该方法默认为false。
        option.setOnceLocation(true);
        mLocationClient.setLocationOption(option);
        mLocationClient.setLocationListener(new AMapLocationListener() {
            public void onLocationChanged(AMapLocation aMapLocation) {
                if (aMapLocation != null) {
                    Log.e("xyd", "ErrorCode = " + aMapLocation.getErrorCode());
                    Log.e("xyd", "LocationDetail = " + aMapLocation.getLocationDetail());
                    if (aMapLocation.getErrorCode() == 0) {

                        // 纬度
                        latitude = aMapLocation.getLatitude();
                        // 经度
                        longitude = aMapLocation.getLongitude();

                        mStartPoint = new LatLonPoint(longitude, latitude);
                    } else {
                        //mContext.mCityAdapter.updateLocateState(666, (String) null);
                    }
                }

            }
        });
        mLocationClient.startLocation();
    }

    //</editor-fold>


    private void getHotelAvailableRoomTypeList() {
        HashMap<String, Object> h1 = new HashMap<>();
        h1.put("token", SharePrefUtil.getString(mContext, ShareKeys.Token, ""));
        h1.put("sessionId", SharePrefUtil.getString(mContext, ShareKeys.sessionId, ""));
        h1.put("hotelUuid", hotelUuid);    //先写死
        h1.put("startDate", startDay);    //开始时间
        h1.put("endDate", endDay);      //结束时间


        Call<HttpResult<ListResult<HotelRoomShowModel>>> call = service.getHotelAvailableRoomTypeList(JsonUtils.convertParam("getHotelAvailableRoomTypeList", h1));
        call.enqueue(new CallbackImpl<ListResult<HotelRoomShowModel>>() {
            @Override
            public void responseSuccess(Call<HttpResult<ListResult<HotelRoomShowModel>>> call, Response<HttpResult<ListResult<HotelRoomShowModel>>> response) {

                if (response.body().getData() != null) {

                    if (groupTittles.size() > 0) {
                        groupTittles.clear();
                    }
                    groupTittles.addAll(response.body().getData().dataList);


                    if (groupDatas.size() > 0) {
                        groupDatas.clear();
                    }
                    for (HotelRoomShowModel groupItem : groupTittles) {
                        ArrayList<HotelRoomTypeShowModel> itemList = (ArrayList<HotelRoomTypeShowModel>) groupItem.roomPrice;
                        groupDatas.add(itemList);
                    }

                    selectHomeExpandableListAdapter.notifyDataSetChanged();

                }

            }
        });
    }

    private void getHotelInfo() {
        HashMap<String, Object> h1 = new HashMap<>();
        h1.put("token", SharePrefUtil.getString(mContext, ShareKeys.Token, ""));
        h1.put("sessionId", SharePrefUtil.getString(mContext, ShareKeys.sessionId, ""));
        h1.put("hotelUuid", hotelUuid);

        Call<HttpResult<HotelInfo>> call = service.getHotelInfo(JsonUtils.convertParam("getHotelInfo", h1));
        call.enqueue(new CallbackImpl<HotelInfo>() {
            @Override
            public void responseSuccess(Call<HttpResult<HotelInfo>> call, Response<HttpResult<HotelInfo>> response) {

                HotelInfo hotelInfo = response.body().getData();
                if (hotelInfo != null) {
                    tvDetailTitle.setText(hotelInfo.hotelName);
                    tv_location_name.setText("不知道什么商圈");
                    tvHotelPoint.setText(hotelInfo.hotelScore + "分" + hotelInfo.hotelScoreLevel);
                    tvEvaluate.setText(hotelInfo.appsCount + "条点评");
                    tvOpenTime.setText(hotelInfo.openYear + "年开业");
                    ImageUtil.displayImage(hotelInfo.HotelPicPath, ivHotelLogo);
                    mEndPoint = new LatLonPoint(Double.parseDouble(hotelInfo.longitude), Double.parseDouble(hotelInfo.latitude));
                }
            }
        });
    }

    private void initView() {

        groupTittles = new ArrayList<>();

        groupDatas = new ArrayList<>();


        selectHomeExpandableListAdapter = new HotelDetailExpandableListAdapter(mContext);
        selectHomeExpandableListAdapter.setGroupData(groupDatas);
        selectHomeExpandableListAdapter.setGroupTittleData(groupTittles);

        elRooms.setAdapter(selectHomeExpandableListAdapter);
        //CommonUtil.setListViewHeightBasedOnChildren(elRooms);


        startDay = DateTimeUtil.format("yyyy-MM-dd", DateTimeUtil.getCurrentTime());
        tvLiveTime.setText(DateTimeUtil.format(startDay, "yyyy-MM-dd", "yyyy年MM月dd日").substring(5));
        endDay = DateTimeUtil.format("yyyy-MM-dd", DateTimeUtil.getCurrentTime() + 60 * 60 * 24 * 1000);
        tvLeaveTime.setText(DateTimeUtil.format(endDay, "yyyy-MM-dd", "yyyy年MM月dd日").substring(5));

        selectHomeExpandableListAdapter.setPreString(hotelUuid, startDay, endDay);
    }

    @OnClick({R.id.btn_left, R.id.tv_evaluate, R.id.tv_hotel_detail_device,
            R.id.tv_live_time, R.id.tv_live_weekday, R.id.tv_live_ok,
            R.id.tv_leave_time, R.id.tv_leave_weekday, R.id.tv_leave_ok,
            R.id.tv_collect, R.id.tv_share, R.id.cl_ask})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_left:
                break;
            case R.id.tv_evaluate:
                Intent intent1 = new Intent(mContext, HotelEvaluateActivity.class);
                mContext.startActivity(intent1);
                break;
            case R.id.tv_hotel_detail_device:
                Intent intent2 = new Intent(mContext, HotelDetailAndDeviceActivity.class);
                intent2.putExtra("hotelUuid", hotelUuid);
                mContext.startActivity(intent2);
                break;

            case R.id.tv_live_time:
            case R.id.tv_live_weekday:
            case R.id.tv_live_ok:
                setStartDay();
                break;
            case R.id.tv_leave_time:
            case R.id.tv_leave_weekday:
            case R.id.tv_leave_ok:
                setEndDay();
                break;
            case R.id.tv_collect:
                break;
            case R.id.tv_share:
                break;
            case R.id.cl_ask:   // 问大家

                Intent intent = new Intent(mContext, AskActivity.class);
                mContext.startActivity(intent);
                break;
        }
    }

    /**
     * 选择起始时间
     */
    private void setStartDay() {
        DatePickerPopWin pickerPopWin = new DatePickerPopWin.Builder(mContext, new DatePickerPopWin.OnDatePickedListener() {
            @Override
            public void onDatePickCompleted(int year, int month, int day, String dateDesc) {

                if (DateTimeUtil.getCurrentTime() - 3600 * 24 * 1000 > DateTimeUtil.stringToMillionSeconds("yyyy-MM-dd", dateDesc)) {
                    ToastUtil.showShortToast(mContext, "请选择今天或者今天之后的日期");
                } else {
                    // 选择正确才赋值
                    startDay = dateDesc;
                    tvLiveTime.setText(DateTimeUtil.format(startDay, "yyyy-MM-dd", "yyyy年MM月dd日").substring(5));
                    selectHomeExpandableListAdapter.setPreString(hotelUuid, startDay, endDay);
                }
            }
        }).textConfirm("确认") //text of confirm button
                .textCancel("取消") //text of cancel button
                .btnTextSize(15) // button text size
                .viewTextSize(25) // pick view text size
                .colorCancel(Color.parseColor("#999999")) //color of cancel button
                .colorConfirm(Color.parseColor("#7966ca"))//color of confirm button
                .minYear(DateTimeUtil.getYear(DateTimeUtil.getCurrentTime())) //min year in loop
                .maxYear(DateTimeUtil.getYear(DateTimeUtil.getCurrentTime()) + 2) // max year in loop
                .dateChose(startDay) // date chose when init popwindow
                .build();

        pickerPopWin.showPopWin(mContext);
    }

    /**
     * 选择结束时间
     */
    private void setEndDay() {
        DatePickerPopWin pickerPopWin = new DatePickerPopWin.Builder(mContext, new DatePickerPopWin.OnDatePickedListener() {
            @Override
            public void onDatePickCompleted(int year, int month, int day, String dateDesc) {
                LogUtil.e("xyd", "dateDesc = " + DateTimeUtil.getTimeMills(dateDesc));

                if (DateTimeUtil.getCurrentTime() - 3600 * 24 * 1000 > DateTimeUtil.stringToMillionSeconds("yyyy-MM-dd", dateDesc)) {
                    ToastUtil.showShortToast(mContext, "请选择入住日之后的日期");
                } else {
                    // 选择正确才赋值
                    endDay = dateDesc;
                    tvLeaveTime.setText(DateTimeUtil.format(endDay, "yyyy-MM-dd", "yyyy年MM月dd日").substring(5));
                    selectHomeExpandableListAdapter.setPreString(hotelUuid, startDay, endDay);

                }

            }
        }).textConfirm("确认") //text of confirm button
                .textCancel("取消") //text of cancel button
                .btnTextSize(15) // button text size
                .viewTextSize(25) // pick view text size
                .colorCancel(Color.parseColor("#999999")) //color of cancel button
                .colorConfirm(Color.parseColor("#7966ca"))//color of confirm button
                .minYear(DateTimeUtil.getYear(DateTimeUtil.getCurrentTime())) //min year in loop
                .maxYear(DateTimeUtil.getYear(DateTimeUtil.getCurrentTime()) + 2) // max year in loop
                .dateChose(endDay) // date chose when init popwindow
                .build();

        pickerPopWin.showPopWin(mContext);
    }


    /**
     * 方法必须重写
     */
    @Override
    protected void onResume() {
        super.onResume();
        mapView.onResume();
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onPause() {
        super.onPause();
        mapView.onPause();
    }

    @Override
    public View getInfoContents(Marker arg0) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public View getInfoWindow(Marker arg0) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public void onInfoWindowClick(Marker arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public boolean onMarkerClick(Marker arg0) {
        // TODO Auto-generated method stub
        return false;
    }

    @Override
    public void onMapClick(LatLng arg0) {
        // TODO Auto-generated method stub

    }


    /**
     * 开始搜索路径规划方案
     */
    public void searchRouteResult(int routeType, int mode) {
        if (mStartPoint == null) {
            ToastUtil.showShortToast(mContext, "定位中，稍后再试...");
            return;
        }
        if (mEndPoint == null) {
            ToastUtil.showShortToast(mContext, "终点未设置");
        }
        //showProgressDialog();
        final RouteSearch.FromAndTo fromAndTo = new RouteSearch.FromAndTo(
                mStartPoint, mEndPoint);
        if (routeType == ROUTE_TYPE_DRIVE) {// 驾车路径规划
            DriveRouteQuery query = new DriveRouteQuery(fromAndTo, mode, null,
                    null, "");// 第一个参数表示路径规划的起点和终点，第二个参数表示驾车模式，第三个参数表示途经点，第四个参数表示避让区域，第五个参数表示避让道路
            mRouteSearch.calculateDriveRouteAsyn(query);// 异步路径规划驾车模式查询
        }
    }

    @Override
    public void onBusRouteSearched(BusRouteResult result, int errorCode) {

    }

    @Override
    public void onDriveRouteSearched(DriveRouteResult result, int errorCode) {
        //dissmissProgressDialog();
        aMap.clear();// 清理地图上的所有覆盖物
        if (errorCode == AMapException.CODE_AMAP_SUCCESS) {
            if (result != null && result.getPaths() != null) {
                if (result.getPaths().size() > 0) {
                    mDriveRouteResult = result;
                    final DrivePath drivePath = mDriveRouteResult.getPaths()
                            .get(0);
                    DrivingRouteOverLay drivingRouteOverlay = new DrivingRouteOverLay(
                            mContext, aMap, drivePath,
                            mDriveRouteResult.getStartPos(),
                            mDriveRouteResult.getTargetPos(), null);
                    drivingRouteOverlay.setNodeIconVisibility(false);//设置节点marker是否显示
                    drivingRouteOverlay.setIsColorfulline(true);//是否用颜色展示交通拥堵情况，默认true
                    drivingRouteOverlay.removeFromMap();
                    drivingRouteOverlay.addToMap();
                    drivingRouteOverlay.zoomToSpan();
                    //mBottomLayout.setVisibility(View.VISIBLE);
                    int dis = (int) drivePath.getDistance();
                    int dur = (int) drivePath.getDuration();
                    //String des = AMapUtil.getFriendlyTime(dur)+"("+AMapUtil.getFriendlyLength(dis)+")";
                    tv_km.setText(AMapUtil.getFriendlyLength(dis));
                    tv_time.setText(AMapUtil.getFriendlyTime(dur));
                    //mRouteDetailDes.setVisibility(View.VISIBLE);

                    //int taxiCost = (int) mDriveRouteResult.getTaxiCost();
                    //mRouteDetailDes.setText("打车约"+taxiCost+"元");

                } else if (result != null && result.getPaths() == null) {
                    //ToastUtil.show(mContext, R.string.no_result);
                }

            } else {
                //ToastUtil.show(mContext, R.string.no_result);
            }
        } else {
            //ToastUtil.showerror(this.getApplicationContext(), errorCode);
        }


    }

    @Override
    public void onWalkRouteSearched(WalkRouteResult result, int errorCode) {

    }

    @Override
    public void onRideRouteSearched(RideRouteResult arg0, int arg1) {
        // TODO Auto-generated method stub

    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(String event) {
        if (EventBusKeys.finishPreOrder.equals(event)) {
            finish();
        }
    }
}
